<?php
	include_once('database.php');
	include_once('session_start.php');
	
	$username = trim($_POST["UserName"]);// (QUESTION) TRIM? OR ERROR IF WHITESPACE IS WRITTEN?
	$pass = trim($_POST["Password"]);  // (QUESTION) TRIM? OR ERROR IF WHITESPACE IS WRITTEN?
    $cf_pass = trim($_POST["CF_Password"]);// (QUESTION) TRIM? OR ERROR IF WHITESPACE IS WRITTEN?
    $f_name = $_POST["F_Name"];
    $l_name = $_POST["L_Name"];
    $email = $_POST["E-mail"];
    $country = $_POST["Country"];
    $address = $_POST["Address"];
    $postcode = $_POST["Postal_Code"];
    
    $error= false;
    foreach ($_POST as $key => $value) {
        $_SESSION["Create_User"][$key] = $value;
        if(empty($value)){
            $error = true;
        }
    };
	if($error==true){
		$_SESSION["H7_Library_Message"]="Alle felter skal være udfyldt";
		header('Location:create_user_form.php');
		die;
	}
    if($cf_pass != $pass){
        $_SESSION["H7_Library_Message"]="Passwords matcher ikke. Prøv igen";
        header('Location:create_user_form.php');
        die;        
    }
	$check = $db -> query("SELECT UserName FROM users WHERE UserName = '".mysqli_real_escape_string($db,$username)."';");
	
    if($check -> num_rows != 0){
		$_SESSION["H7_Library_Message"]="Brugeren ".htmlspecialchars($username)." findes allerede";
		header('Location:create_user_form.php');
		die;
	}
	$exp = explode('.', $email);
	$ext = end($exp);    
    $at = explode('@', $email);
    $domain = end($at);
    $dot = explode('.', $domain);
    if(strlen($ext)>4||strpos($email,'@')==false || count($at)>2 || count($dot)>2){
        $_SESSION["H7_Library_Message"]="Den givne email var ikke valid";
        header('Location:create_user_form.php');
        die;
    }
    $query = "INSERT INTO users(UserName, Password, FirstName, LastName, Email, Address, Country, PostalCode)
              VALUES (?, ? , ? ,? ,? ,? ,? ,?)";

    $stmt = $db->prepare($query);
    $stmt-> bind_param('ssssssss',$username,$pass,$f_name,$l_name,$email,$address,$country,$postcode);
    $stmt -> execute();
	$id = $stmt -> insert_id;
	$_SESSION["H7_Library_Message"]="Brugeren ".htmlspecialchars($username)." er oprettet";	

    unset($_SESSION['Create_User']);
  
    $_SESSION["User"] = Array(
                           "Name"=> $username,
                           "Admin"=> 0,
                           "Id"=> $id             
                        );
	header('Location:index.php');
    
?>